import 'dart:async';
 

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:osg/controllers/my_method.dart';

import '/kong.dart' if (dart.library.io) 'package:osg/middleware/im_manager.dart';
import '/kong.dart' if (dart.library.io) 'package:tencent_cloud_chat_sdk/enum/message_elem_type.dart';
import '/kong.dart' if (dart.library.io) 'package:tencent_cloud_chat_sdk/models/v2_tim_conversation.dart';
import '/kong.dart' if (dart.library.io) 'package:tencent_cloud_chat_sdk/models/v2_tim_message.dart';
import '/kong.dart' if (dart.library.io) 'package:tencent_cloud_chat_sdk/models/v2_tim_message.dart';
import '/kong.dart' if (dart.library.io) 'package:tencent_cloud_chat_sdk/models/v2_tim_text_elem.dart';



class ChatMsg extends StatefulWidget {
  const ChatMsg({super.key});

  @override
  State<ChatMsg> createState() => _SettingPageState();
}

class _SettingPageState extends State<ChatMsg> {
  final user = Get.find<MyMethod>().myget('user')??'';
  
  late final String userId;
  late final String groupId;
  late final String conversationId;
  late final String name;

  final _focusNode = FocusNode();
  final ScrollController _scrollController = ScrollController();
  final _contentController = TextEditingController();

  void _scrollToBottom() {
    WidgetsBinding.instance.addPostFrameCallback((_) {
      if (_scrollController.hasClients) {
        _scrollController.animateTo(
           _scrollController.position.maxScrollExtent,
          duration: Duration(milliseconds: 300),
          curve: Curves.easeOut,
        );
      }
    });
  }

  V2TimConversation? _conversationDetails;
  List<V2TimMessage> _historyMessageList = [];

  Future<void> _initMessageList() async {
    await ImManager().addMessageListener(
      onCallback: (V2TimMessage msg) {
        if (mounted) {
          setState(() {
            print('122333');
            _historyMessageList.add(msg);
          });
        }
      },
    );

    await _getConversationDetails();
    await _getHistoryMessageList();
  }
   

final ScrollController t_scrollController = ScrollController();

  Future<void> _getConversationDetails() async {

    if (conversationId.isNotEmpty) {
      _conversationDetails = await ImManager().getConversationDetails(
        conversationId: conversationId,
      );
     
        setState(() {
      
        });
     


// _scrollToBottom();
  //     WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
  //        Timer(Duration(milliseconds:100), () {
  //     t_scrollController.jumpTo(t_scrollController.position.maxScrollExtent);
  //     print('12354');

  // });

  //   });


//  Timer(Duration(seconds:3), () {
//       t_scrollController.jumpTo(t_scrollController.position.maxScrollExtent);
//       print('12354');

//   });

    }
  }

  //  void _scrollToBottom() {
  //   WidgetsBinding.instance.addPostFrameCallback((_) {
  //     if (_scrollController.hasClients) {
  //       _scrollController.animateTo(
  //         _scrollController.position.maxScrollExtent,
  //         duration: Duration(milliseconds: 300),
  //         curve: Curves.easeOut,
  //       );
  //     }
  //   });
  // }

  Future<void> _getHistoryMessageList() async {
    _historyMessageList = await ImManager().getHistoryMessageList(
      userId: userId,
      groupId: groupId,
    );
    print('ddddd');
    if (mounted) {
      setState(() {});
    }

      _scrollToBottom();
  }

  Future<void> _sendMessage() async {
    if (_contentController.text.isNotEmpty) {
      print(_contentController.text);
      final result = await ImManager().sendMessage(
        userId: userId,
        groupId: groupId,
        text: _contentController.text,
      );
      if (result) {

          print(8889991);
          print(user['uuid']);

        final v2TimMessage = V2TimMessage(
            sender: user['uuid'],
            nickName: user['name'],
            elemType: MessageElemType.V2TIM_ELEM_TYPE_TEXT,
            textElem: V2TimTextElem(text: _contentController.text),
            faceUrl: user['headimg']
            );
        setState(() {
          _historyMessageList.add(v2TimMessage);
        });
        _contentController.clear();
        _scrollToBottom();
      }
    }
  }

  _markC2CMessageAsRead(){

  }


  @override
  void initState() {
    super.initState();


    userId = Get.parameters['userid'] ?? '';
    groupId = Get.parameters['groupId'] ?? '';
    name = Get.parameters['name'] ?? '';
    conversationId = Get.parameters['conversationID'] ?? 'c2c_$userId';

    _focusNode.addListener(() {
      if (_focusNode.hasFocus) {
        _scrollToBottom();
      }
    });
    _initMessageList();
    
     _markC2CMessageAsRead();

     ImManager().markC2CMessageAsRead(userID: userId);

     

  }

  @override
void dispose() {
  t_scrollController.dispose();
  _contentController.dispose();
  super.dispose();
}

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Color(0xffffffff),
        centerTitle: true,
        leadingWidth: 40,
        title: Text(
          '${_conversationDetails!.showName??name}',
          style: TextStyle(fontSize: 16),
        ),
        leading: IconButton(
          onPressed: () {
            Get.back();
          },
          icon: Image.asset('static/images/back.png'),
        ),
      ),
      body: Column(
        children: [
          Expanded(
              child: SingleChildScrollView(
              padding: EdgeInsets.symmetric(horizontal: 15),
              controller: _scrollController,
              // itemCount: _historyMessageList.length,
              // itemBuilder: (context, index) {
              child: Column(
                children: [
                      for (var item in _historyMessageList.asMap().entries)
                item.value.sender != user['uuid']
                    ? Row(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          CircleAvatar(
                              radius: 22,
                              backgroundImage:
                                  NetworkImage('${item.value.faceUrl}')),
                          SizedBox(
                            width: 10,
                          ),
                          Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              Container(
                                margin: EdgeInsets.only(bottom: 10),
                                padding: EdgeInsets.symmetric(
                                    vertical: 10, horizontal: 12),
                                decoration: BoxDecoration(
                                    color: Color(0XFFF5F5F5),
                                    borderRadius: BorderRadius.only(
                                      topRight: Radius.circular(10),
                                      bottomLeft: Radius.circular(10),
                                      bottomRight: Radius.circular(10),
                                    )),
                                child: Text(
                                  '${item.value.textElem!.text}',
                                  style: TextStyle(color: Color(0XFF333333)),
                                ),
                              ),
                              // Text(
                              //   '昨天 12:22',
                              //   style: TextStyle(
                              //       fontSize: 12, color: Color(0XFF999999)),
                              // ),
                            ],
                          )
                        ],
                      )
                    : Row(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        mainAxisAlignment: MainAxisAlignment.end,
                        children: [
                          Column(
                            crossAxisAlignment: CrossAxisAlignment.end,
                            children: [
                              Container(
                                margin: EdgeInsets.only(bottom: 10),
                                padding: EdgeInsets.symmetric(
                                    vertical: 10, horizontal: 12),
                                decoration: BoxDecoration(
                                    color: Color(0XFF0A56D9),
                                    borderRadius: BorderRadius.only(
                                      topRight: Radius.circular(10),
                                      bottomLeft: Radius.circular(10),
                                      bottomRight: Radius.circular(10),
                                    )),
                                child: Text(
                                  '${item.value.textElem!.text}',
                                  style: TextStyle(color: Color(0XFFFFFFFF)),
                                ),
                              ),
                              // Text(
                              //   '昨天 12:22',
                              //   style: TextStyle(
                              //       fontSize: 12, color: Color(0XFF999999)),
                              // ),
                            ],
                          ),
                          SizedBox(
                            width: 10,
                          ),
                          CircleAvatar(
                              radius: 22,
                              backgroundImage:
                                  NetworkImage('${item.value.faceUrl}')),
                        ],
                      ),
            
                ],
              )
              //      _historyMessageList[index].sender != user['uuid']
              //       ? Row(
              //           crossAxisAlignment: CrossAxisAlignment.start,
              //           children: [
              //             CircleAvatar(
              //                 radius: 22,
              //                 backgroundImage:
              //                     NetworkImage('${_historyMessageList[index].faceUrl}')),
              //             SizedBox(
              //               width: 10,
              //             ),
              //             Column(
              //               crossAxisAlignment: CrossAxisAlignment.start,
              //               children: [
              //                 Container(
              //                   margin: EdgeInsets.only(bottom: 10),
              //                   padding: EdgeInsets.symmetric(
              //                       vertical: 10, horizontal: 12),
              //                   decoration: BoxDecoration(
              //                       color: Color(0XFFF5F5F5),
              //                       borderRadius: BorderRadius.only(
              //                         topRight: Radius.circular(10),
              //                         bottomLeft: Radius.circular(10),
              //                         bottomRight: Radius.circular(10),
              //                       )),
              //                   child: Text(
              //                     '${_historyMessageList[index].textElem!.text}',
              //                     style: TextStyle(color: Color(0XFF333333)),
              //                   ),
              //                 ),
              //                 // Text(
              //                 //   '昨天 12:22',
              //                 //   style: TextStyle(
              //                 //       fontSize: 12, color: Color(0XFF999999)),
              //                 // ),
              //               ],
              //             )
              //           ],
              //         )
              //       : Row(
              //           crossAxisAlignment: CrossAxisAlignment.start,
              //           mainAxisAlignment: MainAxisAlignment.end,
              //           children: [
              //             Column(
              //               crossAxisAlignment: CrossAxisAlignment.end,
              //               children: [
              //                 Container(
              //                   margin: EdgeInsets.only(bottom: 10),
              //                   padding: EdgeInsets.symmetric(
              //                       vertical: 10, horizontal: 12),
              //                   decoration: BoxDecoration(
              //                       color: Color(0XFF0A56D9),
              //                       borderRadius: BorderRadius.only(
              //                         topRight: Radius.circular(10),
              //                         bottomLeft: Radius.circular(10),
              //                         bottomRight: Radius.circular(10),
              //                       )),
              //                   child: Text(
              //                     '${_historyMessageList[index].textElem!.text}',
              //                     style: TextStyle(color: Color(0XFFFFFFFF)),
              //                   ),
              //                 ),
              //                 // Text(
              //                 //   '昨天 12:22',
              //                 //   style: TextStyle(
              //                 //       fontSize: 12, color: Color(0XFF999999)),
              //                 // ),
              //               ],
              //             ),
              //             SizedBox(
              //               width: 10,
              //             ),
              //             CircleAvatar(
              //                 radius: 22,
              //                 backgroundImage:
              //                     NetworkImage('${_historyMessageList[index].faceUrl}')),
              //           ],
              //         );
            
              // }

            // children: [
            //   for (var item in _historyMessageList.asMap().entries)
            //     item.value.sender != user['uuid']
            //         ? Row(
            //             crossAxisAlignment: CrossAxisAlignment.start,
            //             children: [
            //               CircleAvatar(
            //                   radius: 22,
            //                   backgroundImage:
            //                       NetworkImage('${item.value.faceUrl}')),
            //               SizedBox(
            //                 width: 10,
            //               ),
            //               Column(
            //                 crossAxisAlignment: CrossAxisAlignment.start,
            //                 children: [
            //                   Container(
            //                     margin: EdgeInsets.only(bottom: 10),
            //                     padding: EdgeInsets.symmetric(
            //                         vertical: 10, horizontal: 12),
            //                     decoration: BoxDecoration(
            //                         color: Color(0XFFF5F5F5),
            //                         borderRadius: BorderRadius.only(
            //                           topRight: Radius.circular(10),
            //                           bottomLeft: Radius.circular(10),
            //                           bottomRight: Radius.circular(10),
            //                         )),
            //                     child: Text(
            //                       '${item.value.textElem!.text}',
            //                       style: TextStyle(color: Color(0XFF333333)),
            //                     ),
            //                   ),
            //                   // Text(
            //                   //   '昨天 12:22',
            //                   //   style: TextStyle(
            //                   //       fontSize: 12, color: Color(0XFF999999)),
            //                   // ),
            //                 ],
            //               )
            //             ],
            //           )
            //         : Row(
            //             crossAxisAlignment: CrossAxisAlignment.start,
            //             mainAxisAlignment: MainAxisAlignment.end,
            //             children: [
            //               Column(
            //                 crossAxisAlignment: CrossAxisAlignment.end,
            //                 children: [
            //                   Container(
            //                     margin: EdgeInsets.only(bottom: 10),
            //                     padding: EdgeInsets.symmetric(
            //                         vertical: 10, horizontal: 12),
            //                     decoration: BoxDecoration(
            //                         color: Color(0XFF0A56D9),
            //                         borderRadius: BorderRadius.only(
            //                           topRight: Radius.circular(10),
            //                           bottomLeft: Radius.circular(10),
            //                           bottomRight: Radius.circular(10),
            //                         )),
            //                     child: Text(
            //                       '${item.value.textElem!.text}',
            //                       style: TextStyle(color: Color(0XFFFFFFFF)),
            //                     ),
            //                   ),
            //                   // Text(
            //                   //   '昨天 12:22',
            //                   //   style: TextStyle(
            //                   //       fontSize: 12, color: Color(0XFF999999)),
            //                   // ),
            //                 ],
            //               ),
            //               SizedBox(
            //                 width: 10,
            //               ),
            //               CircleAvatar(
            //                   radius: 22,
            //                   backgroundImage:
            //                       NetworkImage('${item.value.faceUrl}')),
            //             ],
            //           ),
            
            // ],

          )),


          Container(
            margin:
                EdgeInsets.only(bottom: MediaQuery.of(context).padding.bottom),
            padding: EdgeInsets.symmetric(horizontal: 10),
            height: 58,
            alignment: Alignment.center,
            child: Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Expanded(
                  child: Row(
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      Expanded(
                        child: TextFormField(
                          focusNode: _focusNode,
                          controller: _contentController,
                          decoration: InputDecoration(
                            hintText: '请输入内容',
                          ),
                          validator: (value) {
                            if (value == null || value.isEmpty) {
                              return '不能为空';
                            }
                            return null;
                          },
                        ),
                      ),
                    ],
                  ),
                ),
                ElevatedButton(
                  onPressed: _sendMessage,
                  child: Text('发送'),
                ),
              ],
            ),
          )
        ],
      ),
    );
  }
}
